import React,{lazy,Suspense, useEffect, createContext, useMemo} from 'react';
import { BrowserRouter as Router, Route, Routes, matchPath, useRoutes, useNavigate } from 'react-router-dom';
import LoginPage from './pages/LoginPage';
import HomePage from './pages/HomePage';
import DictData from './pages/system/dict/data';
import MainLayout from './layouts/MainLayout';
import About from './pages/About';
import User from './pages/system/user/index';
import { useDispatch, useSelector } from 'react-redux';
import { generateRoutes } from './store/actions/permission';
import { useDict } from './utils/dict';
import { DictContext } from './context/context';
import { addDateRange,handleTree } from './utils/bigwolf';
import { getSystemName } from './utils/config';
// const componentsMap = {
//   'user': lazy(() => import('./pages/system/user/index')),
//   // 可以添加更多组件...
// };
function App() {

  const leafRouters = useSelector(state => state.permission.leafRouters);
  const user = useSelector(state => state.user);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [menuRouters, setMenuRouters] = React.useState(leafRouters);

  useEffect(() => {
    if(!user.token) {
      navigate('/login', { replace: true });
    }
    if (user.token && !menuRouters.length) {
      try {
      dispatch(generateRoutes()).then((response) => {
        //console.log('============response====ggg==',response);
      }
      ).catch(err => {
        //console.log('============errr=1111=====',err);
        //跳转到登陆页面
        navigate('/login', { replace: true });
      })
      ;
    } catch (error) {
      //console.log('============error=aaaa=====',error);
    }
    }
  }, [dispatch, menuRouters]);

  // 监听 Redux 状态变化以更新本地状态
  useEffect(() => {
    setMenuRouters(leafRouters);
  }, [leafRouters]);
  // if(leafRouters.length === 0){
  //   dispatch(generateRoutes());
  // }

  // useEffect(() => {
  //   dispatch(generateRoutes());
  //   //console.log('=======App========');
  // }, [])

  //console.log('====effw===App========');
  //console.log('=======leafRouters========',leafRouters);
  // const componentsMap = leafRouters.reduce((acc, route) => {
  //   // 提取路径的最后一部分作为键名（去掉前面的父级路径）
  //   const key = route.component;//.replace(/.*\//, '');
  //   //console.log('=======key========',route.component);
  //   // 构建import语句的字符串
  //   const importPath = `./pages/${route.component}`;
  //   // 使用eval来动态执行lazy加载包裹并添加到accumulator对象中
  //   acc[key] = lazy(() => import(`${importPath}`));
  //   return acc;
  // }, {});

  const componentsMap = useMemo(() => leafRouters.reduce((acc, route) => {
    const key = route.component;
    const importPath = `./pages/${key}`;
    acc[key] = lazy(() => import(`${importPath}`));
    return acc;
  }, {}), [leafRouters]);

  //console.log('=======componentsMap========',componentsMap);
  const LoadComponent = (componentKey) => {
    const Component = componentsMap[componentKey];
    return Component ? <Suspense fallback={<div>Loading...</div>}><Component /></Suspense> : null;
  };
  return (
    <DictContext.Provider value={{ useDict, addDateRange, handleTree, getSystemName }}>
      {/* <Router> */}
      {/* <Suspense fallback={<div>Loading...</div>}> */}
        <Routes>
        <Route path="/" element={<MainLayout/>}>
          <Route index element={<HomePage/>} />
          <Route path="/about" element={<About />} />
          {/* <Route path="/user" element={LoadComponent('user')} /> */}
          {leafRouters.map(route => (
            <Route 
              key={route.component} 
              path={"/" + route.component} // 确保路径格式正确
              element={LoadComponent(route.component)} // 使用去掉父级路径后的键名
            />
          ))}
          {/* <Route path="/user" element={<User/>} /> */}
          
          <Route path="/system/dict-data">
            <Route path="index/:dictId" element={<DictData />} />
          </Route>
        </Route>
        <Route path="/login" element={<LoginPage/>} />
        </Routes>
        {/* </Suspense> */}
      {/* </Router> */}
      </DictContext.Provider>
  );
}


export default App;